<?php
namespace app\mp\admin;

use app\system\admin\Admin;
use app\common\service\Material as MaterialService;
use app\common\service\Order as OrderService;
use app\common\service\OrderMaterial as OrderMaterialService;
use app\common\service\OrderMaterialItem as OrderMaterialItemService;
use app\common\service\CheckclothShrink as CheckclothShrinkService;
use app\common\service\Rejects as RejectsService;
use app\common\service\MaterialReturn as MaterialReturnService;

class Shrink extends Admin
{

    public function initialize() {
    	parent::initialize();
    }

    /**
     * 缩水区主页
     */
    public function index() {
    	$assign = [
    		'rejectsKV' => getRejectsKV(),
    	];
    	$assign['rejectsCount'] = count($assign['rejectsKV']);
    	return $this->assign($assign)->fetch();
    }

    /**
     * 次品退
     *
     * @author KING
     * @date 2020年4月24日
     *
     */
    public function rejects() {
    	$isReturn = intval($this->request->param('is_return/d', 0));
    	$clientOrdernum = $this->request->param('client_ordernum/s', '');
    	$materialId = intval($this->request->param('material_id/d', 0));
    	$clothNum = intval($this->request->param('cloth_num/d', 0));
    	$edgeDamage = floatval($this->request->param('edge_damage/d', 0));
    	$weightShrink = floatval($this->request->param('weight_shrink/d', 0));
    	$weightPage = floatval($this->request->param('weight_page/d', 0));
    	$lengthShrink = floatval($this->request->param('length_shrink/d', 0));
    	$length = floatval($this->request->param('length/d', 0));
    	$trueFabricWidth = floatval($this->request->param('true_fabric_width/d', 0));
    	$fabricWidthShrink = floatval($this->request->param('fabric_width_shrink/d', 0));
    	$reason=$this->request->param('rejects_id', []);
        $reason=count($reason) >0 ? implode(',',$reason) : ''; //退料原因
    	$orderService = new OrderService();
    	$materialService = new MaterialService();
    	$rejectsService = new RejectsService();
    	$orderMaterialService = new OrderMaterialService();
    	$orderMaterialItemService = new OrderMaterialItemService();
    	$checkclothShrinkService = new CheckclothShrinkService();
    	$orderInfo = $orderService->getInfoByClientOrdernum($clientOrdernum);
    	$orderId = $orderInfo['id'];

    	// 当前实际克重= （缩前重量/kg - 纸筒重量/kg)/(缩前米长 X （缩前布封 / 100)) X1000
    	$trueWeight = round(($weightShrink - $weightPage) / ($lengthShrink * ($fabricWidthShrink /100)) * 1000, 2);
    	$materialInfo = $materialService->getInfoById($materialId, "weight");
    	$weight = $materialInfo['weight'];
    	// 克重超标
    	$weightOver = round(($trueWeight-$weight), 2);

    	// 判断是否多料
    	$confirm = $this->request->param('confirm/d', 0);
    	if (!$confirm) {
	    	$lengthOverMessage = '';
	    	if (db('order_material_item')->where("order_id = {$orderId} and material_id = {$materialId} and is_shrink = 0")->count() > 1) { // 至少有两个未缩的布号，才做提醒
	    		$lengthNow = db('checkcloth_shrink')->where("order_id = {$orderId} and material_id = {$materialId} and type = 2 and is_return = 0")->sum("length");
	    		$lengthNow += $length;
	    		$caigouCount = $orderMaterialService->getNeedDosage($orderId, $materialId);
	    		if ($lengthNow/$caigouCount >= 0.8 && $lengthNow/$caigouCount <= 1) $lengthOverMessage = '多料，继续操作需低于'.($caigouCount-$lengthNow).'米';
	    		elseif ($lengthNow/$caigouCount > 1) {
	    			$lengthOverMessage = '超料，请停止操作';
	    		}
	    		if ($lengthOverMessage != '') {
	    			return $this->Json(-1, $lengthOverMessage);
	    		}
	    	}
    	}


    	if ($this->request->isAjax()) {
    		if (!$orderInfo) {
    			return $this->Json(0, '订单号不存在！');
    		}

    		if (empty($materialId)) {
    			return $this->Json(0, '未选择面料！');
    		}

    		if (empty($clothNum) || !is_numeric($clothNum)) {
    			return $this->Json(0, '布号错误！');
    		}

    		$length = round(floatval($length), 2);
    		$trueFabricWidth = round(floatval($trueFabricWidth), 2);
    		$weightShrink = round(floatval($weightShrink), 2);
    		$weightPage = round(floatval($weightPage), 2);
    		$edgeDamage = round(floatval($edgeDamage), 2);

    		if ($length > 300 || $length < 1) {
    			return $this->Json(0, '缩水米长范围只能是1-300！');
    		}
    		if ($lengthShrink > 300 || $lengthShrink < 1) {
    			return $this->Json(0, '缩前米长范围只能是1-300！');
    		}
    		if ($trueFabricWidth > config('mp.fabric_width_max') || $trueFabricWidth < config('mp.fabric_width_min')) {
    			return $this->Json(0, '缩后布封范围只能是'.config('mp.fabric_width_min').'-'.config('mp.fabric_width_max').'！');
    		}
    		if ($fabricWidthShrink > config('mp.fabric_width_max') || $fabricWidthShrink < config('mp.fabric_width_min')) {
    			return $this->Json(0, '缩前布封范围只能是'.config('mp.fabric_width_min').'-'.config('mp.fabric_width_max').'！');
    		}
    		if ($edgeDamage > 8 || $edgeDamage < 0) {
    			return $this->Json(0, '布边损料范围只能是0-8！');
    		}
    		if ($weightShrink > 50 || $weightShrink < 0) {
    			return $this->Json(0, '缩前重量范围只能是0-50！');
    		}
    		if ($weightPage > 3 || $weightPage < 0) {
    			return $this->Json(0, '纸筒重量范围只能是0-3！');
    		}

    		$rejectsIds = $this->request->param('rejects_id/a', []);
    		$rejectsLength = floatval($this->request->param('rejects_length/d', 0));
    		if (empty($rejectsIds)) {
    			return $this->Json(0, '请选择次品类型！');
    		}
    		if ($rejectsLength == '' || !is_numeric($rejectsLength)) {
    			return $this->Json(0, '请填写次品米数！');
    		}

    		// 是否已退料
    		$info = db('checkcloth_shrink')->where("order_id = {$orderId} and material_id = {$materialId} and cloth_num = {$clothNum} and is_return = 1")->findOrEmpty();
    		if ($info) {
    			return $this->Json(0, '该物料布号已退料！');
    		}

    		$info = db('checkcloth_shrink')->where("order_id = {$orderId} and material_id = {$materialId} and type = 2 and cloth_num = {$clothNum}")->findOrEmpty();
    		if ($info) {
    			return $this->Json(0, '该物料布号已处理！');
    		}
    		$orderMaterialItemId = $orderMaterialItemService->getIdByClothNum($orderId, $materialId, $clothNum);
    		if (!$orderMaterialItemId) {
    			return $this->Json(0, '布号数据错误！');
    		}
    		$omiInfo = $orderMaterialItemService->getInfoById($orderMaterialItemId);
            if ($omiInfo['flag_del'] == 1) {
                return $this->Json(0, '此布号已删除！');
            }
    		try {
    			db()->startTrans();
	    		$insData = [
	    			'order_id' => $orderId,
	    			'client_ordernum' => $clientOrdernum,
	    			'type' => 2,
	    			'order_material_item_id' => $orderMaterialItemId,
	    			'cloth_num' => $clothNum,
	    			'material_id' => $materialId,
	    			'stalls_id' => arrayGet($omiInfo, 'stalls_id', 0),
	    			'weight_shrink' => $weightShrink,
	    			'weight_page' => $weightPage,
	    			'length' => $length,
	    			'length_shrink' => $lengthShrink,
	    			'true_fabric_width' => $trueFabricWidth,
	    			'fabric_width_shrink' => $fabricWidthShrink,
	    			'is_return' => 1,
	    			'is_rejects' => 1,
	    			'rejects_ids' => implode(',', $rejectsIds),
	    			'rejects_length' => round($rejectsLength, 2),
	    			'true_weight' => $trueWeight,
	    			'weight_over' => $weightOver,
	    			'admin_id' => ADMIN_ID,
	    			'create_time' => time(),
	    			'update_time' => time(),
	    		];
	    		$result = db('checkcloth_shrink')->insertGetId($insData);

	    		// 标记退料
	    		if ($orderMaterialItemId) {
	    			$omiData = [
	    				'shrink_id' => $result,
	    				'is_return' => 1,
	    				'is_shrink' => 1,
	    				'shrink_time' => time(),
	    				'update_time' => time()
	    			];
	    			db('order_material_item')->where('id', $orderMaterialItemId)->update($omiData);
	    		}

	    		$omInfo = $orderMaterialService->getInfoByOrderIdMaterialId($orderId, $materialId);
                if ($omInfo){
                    $upData = [
                        'return_notconfirm' => 1, //用于标记[待退料审核标记]
                        'update_time' => time(),
                    ];
                    db('order_material')->where('mid', $omInfo['mid'])->update($upData);
                }

	    		// 扣除条数(20200928修改为在 退料进度 确认退料后扣除条数)
	    		/*
	    		if ($omInfo && $omInfo['tiaoshu'] > 0) {
	    			$omData = [
	    				'tiaoshu' => $omInfo['tiaoshu']-1,
	    				'shiji_caigou_count' => $omInfo['tiaoshu']-1,
	    				'tiaoshu_detail' => $omInfo['tiaoshu_detail'] . '-1',
	    			];
	    			db('order_material')->where(['order_id' => $orderId, 'material_id' => $materialId])->update($omData);
	    		} */

	    		//同步到采购备忘
	    		$materialInfo = $materialService->getInfoById($materialId, 'name');
	    		$memoData = [
	    			'order_id' => $orderInfo['id'],
	    			'client_ordernum' => $clientOrdernum,
	    			'content' => "物料[".$materialInfo['name']."]缩水区布号[{$clothNum}]次品退料{$rejectsLength}米（".$reason."）",//$rejectsService->getNameStr($rejectsIds)
	    			'status' => 0,
	    			'create_time' => time(),
	    			'update_time' => time(),
	    			];
	    		db('memo')->insertGetId($memoData);

	    		// 同步到退料进度表里
	    		$mrData = [
	    			'material_id' => $materialId,
	    			'order_id' => $orderId,
	    			'client_ordernum' => $clientOrdernum,
	    			'order_material_id' => $omInfo['mid'],
	    			'order_material_item_id' => $orderMaterialItemId,
	    			'cloth_num' => $clothNum,
	    			'type' => 1,
	    			'reason' => $reason,//$rejectsService->getNameStr($rejectsIds)
	    			'admin_id' => ADMIN_ID,
	    			'status' => 0,
	    			'is_reduce' => 0,
	    			'create_time' => time(),
	    			'update_time' => time(),
	    		];
	    		$materialReturnId = db('material_return')->insertGetId($mrData);

	    		// 记录退料操作日志
	    		(new MaterialReturnService())->addLog($materialReturnId, 1);

	    		// 更新布号米长
	    		$orderMaterialItemService->updateLength($orderId, $materialId);

	    		// 同步数据
	    		$checkclothShrinkService->syncData($orderId, $materialId, 0);

	    		$this->addOrderLog($orderInfo['id'], $clientOrdernum, $memoData['content']);
	    		db()->commit();
	    		return $this->Json(1, '添加次品退料信息 ID' . $result . ' 成功');
    		} catch (\Exception $e) {
    			db()->rollback();
    			return $this->Json(0, '操作失败，'. $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    		}
    	}
    }

    /**
     * 获取今日缩水记录
     *
     * @author KING
     * @date 2020年4月24日
     *
     */
    public function todayLog(){
    	$data = [];
    	$page       = $this->request->param('page/d', 1);
    	$limit      = $this->request->param('limit/d', 20);
    	$dayStart = strtotime('0 day 00:00:00');
    	$dayEnd = $dayStart + 86400;
    	$where = [
    		['type', '=', 2],
    		['create_time', 'between', [$dayStart, $dayEnd]],
    	];
    	$list = db('checkcloth_shrink')->where($where)->page($page)->limit($limit)->order('id desc')->select();
    	$data['count'] = db('checkcloth_shrink')->where($where)->count('id');

    	$materialService = new MaterialService();
    	$orderService = new OrderService();
    	$n=0;
    	foreach ($list as &$v) {
    		$v['seq'] = $data['count']-($page-1)*$limit-$n;
    		$mInfo = $materialService->getInfoById($v['material_id'], 'name');
    		$v['material_name'] = $mInfo['name'];
            if ($v['stock_m_type'] == 0) {
                $oInfo = $orderService->getInfoById($v['order_id'], 'caichuang_type');
                $v['caichuang_type_text'] = arrayGet(config('mimo.caichuang_type'), $oInfo['caichuang_type'], '');
            }
    		$n++;
    	}

    	$data['data'] = $list;
    	$data['code'] = 0;
    	$data['msg'] = '';
    	return json($data);
    }

    /**
     * 保存缩水数据
     *
     * @author KING
     * @date 2020年4月24日
     *
     */
    public function save() {
    	$clientOrdernum = $this->request->param('client_ordernum/s', '');
    	$materialId = $this->request->param('material_id/d', 0);
    	$clothNum = $this->request->param('cloth_num/d', 0);
    	$length = $this->request->param('length/s', 0);
    	$trueFabricWidth = $this->request->param('true_fabric_width/s', 0);
    	$lengthShrink = $this->request->param('length_shrink/s', 0);
    	$fabricWidthShrink = $this->request->param('fabric_width_shrink/s', 0);
    	$weightShrink = $this->request->param('weight_shrink/s', 0);
    	$weightPage = $this->request->param('weight_page/s', 0);
    	$edgeDamage = $this->request->param('edge_damage/s', 0);
        //备料的缩水完成
        $info=db('order_material')->where('mid', substr($clientOrdernum, 1, 100))->find();
        if (substr($clientOrdernum, 0, 1) == 'B' && !empty($info['material_id']) ) { //是备料的验布
            return $this->save_stock_m_type_1();
        }

    	$orderService = new OrderService();
    	$materialService = new MaterialService();
    	$orderMaterialService = new OrderMaterialService();
    	$orderMaterialItemService = new OrderMaterialItemService();
    	$checkclothShrinkService = new CheckclothShrinkService();
		$orderInfo = $orderService->getInfoByClientOrdernum($clientOrdernum);
		$orderId = $orderInfo['id'];
		// 判断是否少料
    	$confirm = $this->request->param('confirm/d', 0);
//    	if (!$confirm) {
//	    	$lengthOverMessage = '';
//	    	if (db('order_material_item')->where("order_id = {$orderId} and material_id = {$materialId} and is_shrink = 0")->count() == 1 ) { // 至少有两个未缩的布号，才做提醒
//	    		$lengthNow = db('checkcloth_shrink')->where("order_id = {$orderId} and material_id = {$materialId} and type = 2 and is_return = 0")->sum("length");
//	    		$lengthNow += $length;
//	    		$caigouCount = $orderMaterialService->getNeedDosage($orderId, $materialId);//dump($lengthNow);dump($caigouCount);
//	    		if ($lengthNow/$caigouCount < 0.85 ) $lengthOverMessage = '少料，想要继续操作还需'.($caigouCount-$lengthNow).'米';
//
//	    		if ($lengthOverMessage != '') {
//	    			return $this->Json(-2, $lengthOverMessage);
//	    		}
//	    	}
//    	}
    	if (!$orderInfo) {
    		return $this->Json(0, '订单号不存在！');
    	}
    	$orderId = $orderInfo['id'];
		$systemUserKV = getSystemUserKV(null);
//		if($orderService->checkExceptionStatus($orderInfo['id'])) return $this->Json(0, "此单异常不允许操作，请找". arrayGet($systemUserKV,config('mp.order_exception_admin_id'),'邓昆明')."解决");//检查订单是否异常
    	if (empty($materialId)) {
    		return $this->Json(0, '未选择面料！');
    	}

    	if (empty($clothNum) || !is_numeric($clothNum)) {
    		return $this->Json(0, '布号错误！');
    	}
    	$lengthShrink = round(floatval($lengthShrink), 2);
    	$fabricWidthShrink = round(floatval($fabricWidthShrink), 2);
    	$length = round(floatval($length), 2);
    	$trueFabricWidth = round(floatval($trueFabricWidth), 2);
    	$weightShrink = round(floatval($weightShrink), 2);
    	$weightPage = round(floatval($weightPage), 2);
    	$edgeDamage = round(floatval($edgeDamage), 2);
    	if ($length > 300 || $length < 1) {
    		return $this->Json(0, '缩后米长范围只能是1-300！');
    	}
    	if ($lengthShrink > 300 || $lengthShrink < 1) {
    		return $this->Json(0, '缩前米长范围只能是1-300！');
    	}
    	if ($fabricWidthShrink > config('mp.fabric_width_max') || $fabricWidthShrink < config('mp.fabric_width_min')) {
    		return $this->Json(0, '缩前布封范围只能是'.config('mp.fabric_width_min').'-'.config('mp.fabric_width_max').'！');
    	}
    	if ($trueFabricWidth > config('mp.fabric_width_max') || $trueFabricWidth < config('mp.fabric_width_min')) {
    		return $this->Json(0, '缩后布封范围只能是'.config('mp.fabric_width_min').'-'.config('mp.fabric_width_max').'！');
    	}
    	if ($edgeDamage > 8 || $edgeDamage < 0) {
    		return $this->Json(0, '布边损料范围只能是0-8！');
    	}
    	if ($weightShrink > 50 || $weightShrink < 0) {
    		return $this->Json(0, '缩前重量范围只能是0-50！');
    	}
    	if ($weightPage > 3 || $weightPage < 0) {
    		return $this->Json(0, '纸筒重量范围只能是0-3！');
    	}

    	$rejectsIds = $this->request->param('rejects_id/a', []);
    	$rejectsLength = $this->request->param('rejects_length/d', 0);
    	if (!is_numeric($rejectsLength)) {
    		return $this->Json(0, '请填写次品米数！');
    	}

    	$omInfo = $orderMaterialService->getInfoByOrderIdMaterialId($orderId, $materialId);
    	if (empty($omInfo)) {
    		return $this->Json(0, '材料数据异常！');
    	}

    	$info = db('checkcloth_shrink')->where("order_id = {$orderId} and material_id = {$materialId} and type = 2 and cloth_num = {$clothNum} and is_return = 0")->field('id')->findOrEmpty();            //dump($info);
    	if ($info) {
    		return $this->Json(0, '该布号已处理！');
    	} else {
    		$orderMaterialItemId = $orderMaterialItemService->getIdByClothNum($orderId, $materialId, $clothNum);
    		if (!$orderMaterialItemId) {
    			return $this->Json(0, '布号数据错误！');
    		}
            $omiInfo = $orderMaterialItemService->getInfoById($orderMaterialItemId);
            if ($omiInfo['flag_del'] == 1) {
                return $this->Json(0, '此布号已删除！');
            }

    		try {
    			db()->startTrans();

	    		// 当前实际克重 =（缩水前重量/kg - 纸筒重量/kg)/(缩后米长 X （缩后布封 / 100)) X1000
	    		$trueWeight = round(($weightShrink - $weightPage) / ($length * ($trueFabricWidth /100))  * 1000, 2);
	    		// 公司克重
	    		$materialInfo = $materialService->getInfoById($materialId, "weight,name,color");
	    		$weight = $materialInfo['weight'];
	    		// 克重超标率
	    		$weightOver = round(($trueWeight-$weight), 2);

	    		$omiInfo = $orderMaterialItemService->getInfoById($orderMaterialItemId);
				if ($omiInfo['need_checkcloth']==1 && $omiInfo['is_checkcloth']==0) {
					return $this->Json(0, '请验布完成再操作！');
				}
	    		$insData = [
	    			'order_id' => $orderId,
	    			'client_ordernum' => $orderInfo['client_ordernum'],
	    			'type' => 2,
	    			'order_material_item_id' => $orderMaterialItemId,
	    			'cloth_num' => $clothNum,
	    			'material_id' => $materialId,
	    			'stalls_id' => arrayGet($omiInfo, 'stalls_id', 0),
	    			'length' => round($length, 2),
	    			'length_shrink' => round($lengthShrink, 2),
	    			'true_fabric_width' => round($trueFabricWidth, 2),
	    			'fabric_width_shrink' => round($fabricWidthShrink, 2),
	    			'weight_shrink' => round($weightShrink, 2),
	    			'weight_page' => round($weightPage, 2),
	    			'edge_damage' => intval($edgeDamage),
	    			'is_rejects' => $rejectsLength > 0 ? 1 : 0,
	    			'rejects_ids' => $rejectsIds ? implode(',', $rejectsIds) : '',
	    			'rejects_length' => round($rejectsLength, 2),
	    			'true_weight' => $trueWeight,
	    			'weight_over' => $weightOver,
	    			'admin_id' => ADMIN_ID,
	    			'create_time' => time(),
	    			'update_time' => time(),
	    		];
	    		$checkclothShrinkId = db('checkcloth_shrink')->insertGetId($insData);

	    		// 标记布号已缩水
	    		if ($orderMaterialItemId) {
	    			$omiData = [
	    				'shrink_id' => $checkclothShrinkId,
	    				'is_shrink' => 1,
	    				'shrink_time' => time(),
	    				'update_time' => time()
	    			];
	    			db('order_material_item')->where('id', $orderMaterialItemId)->update($omiData);
	    		}

	    		// 多料判断及处理
	    		$checkclothShrinkService->excess($orderId, $materialId);

	    		// 更新布号米长
	    		$orderMaterialItemService->updateLength($orderId, $materialId);

	    		// 同步数据
	    		$checkclothShrinkService->syncData($orderId, $materialId,2);
				$orderMaterialService->updateCaichuangStatusV2($orderId,$omInfo['mid'],$this);
				$exception=0;$msg="";
				$dif1 = $orderMaterialService->checkShrinkLossStatus1($omInfo['mid']);
				if ($dif1) {
					$exception=1;//缩水1损耗大于0.02 true=1 ,false=0
					$msg="该单物料亏损严重，差异".$dif1."公斤</br>";
				}
				$dif2 = $orderMaterialService->checkShrinkLossStatus2($omInfo['mid']);
				if ($dif2) {
					$exception=1;
					$msg=$msg."该单物料亏损严重，差异".$dif2."克重";
				}
	    		$this->addOrderLog($orderId, '', "保存物料[".getMaterialName($materialId)."]布号{$clothNum}缩水数据，缩水记录ID {$checkclothShrinkId}");
	    		db()->commit();
	    		return $this->Json(1, '操作成功',['exception'=>$exception,'msg'=>$msg]);
    		} catch (\Exception $e) {
    			db()->rollback();
    			return $this->Json(0, '操作失败，'. $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    		}
    	}

    }

    /**
     * 备料的缩水完成
     * @param $param
     * @author zhuguosen 905502314@qq.com
     * @date 2022/6/20
     */
    private function save_stock_m_type_1()
    {
        $clientOrdernum = $this->request->param('client_ordernum/s', '');
        $materialId = $this->request->param('material_id/d', 0);
        $clothNum = $this->request->param('cloth_num/d', 0);
        $length = $this->request->param('length/s', 0);
        $trueFabricWidth = $this->request->param('true_fabric_width/s', 0);
        $lengthShrink = $this->request->param('length_shrink/s', 0);
        $fabricWidthShrink = $this->request->param('fabric_width_shrink/s', 0);
        $weightShrink = $this->request->param('weight_shrink/s', 0);
        $weightPage = $this->request->param('weight_page/s', 0);
        $edgeDamage = $this->request->param('edge_damage/s', 0);
        // 判断是否少料
        $confirm = $this->request->param('confirm/d', 0);

        $orderService = new OrderService();
        $materialService = new MaterialService();
        $orderMaterialService = new OrderMaterialService();
        $orderMaterialItemService = new OrderMaterialItemService();
        $checkclothShrinkService = new CheckclothShrinkService();

        $systemUserKV = getSystemUserKV(null);
        if (empty($materialId)) {
            return $this->Json(0, '未选择面料！');
        }

        if (empty($clothNum) || !is_numeric($clothNum)) {
            return $this->Json(0, '布号错误！');
        }
        $lengthShrink = round(floatval($lengthShrink), 2);
        $fabricWidthShrink = round(floatval($fabricWidthShrink), 2);
        $length = round(floatval($length), 2);
        $trueFabricWidth = round(floatval($trueFabricWidth), 2);
        $weightShrink = round(floatval($weightShrink), 2);
        $weightPage = round(floatval($weightPage), 2);
        $edgeDamage = round(floatval($edgeDamage), 2);
        if ($length > 300 || $length < 1) {
            return $this->Json(0, '缩后米长范围只能是1-300！');
        }
        if ($lengthShrink > 300 || $lengthShrink < 1) {
            return $this->Json(0, '缩前米长范围只能是1-300！');
        }
        if ($fabricWidthShrink > config('mp.fabric_width_max') || $fabricWidthShrink < config('mp.fabric_width_min')) {
            return $this->Json(0, '缩前布封范围只能是' . config('mp.fabric_width_min') . '-' . config('mp.fabric_width_max') . '！');
        }
        if ($trueFabricWidth > config('mp.fabric_width_max') || $trueFabricWidth < config('mp.fabric_width_min')) {
            return $this->Json(0, '缩后布封范围只能是' . config('mp.fabric_width_min') . '-' . config('mp.fabric_width_max') . '！');
        }
        if ($edgeDamage > 8 || $edgeDamage < 0) {
            return $this->Json(0, '布边损料范围只能是0-8！');
        }
        if ($weightShrink > 50 || $weightShrink < 0) {
            return $this->Json(0, '缩前重量范围只能是0-50！');
        }
        if ($weightPage > 3 || $weightPage < 0) {
            return $this->Json(0, '纸筒重量范围只能是0-3！');
        }

        $rejectsIds = $this->request->param('rejects_id/a', []);
        $rejectsLength = $this->request->param('rejects_length/d', 0);
        if (!is_numeric($rejectsLength)) {
            return $this->Json(0, '请填写次品米数！');
        }

        $omInfo = $orderMaterialService->getInfoById(substr($clientOrdernum, 1, 10));
        if (empty($omInfo)) {
            return $this->Json(0, '材料数据异常！');
        }

        $info = db('checkcloth_shrink')->where("order_material_id = {$omInfo['mid']} and type = 2 and cloth_num = {$clothNum} and is_return = 0")->field('id')->findOrEmpty();            //dump($info);
        if ($info) {
            return $this->Json(0, '该布号已处理！');
        } else {
            $orderMaterialItemId = $orderMaterialItemService->getIdByClothNum(0, 0, $clothNum, $omInfo['mid']);
            if (!$orderMaterialItemId) {
                return $this->Json(0, '布号数据错误！');
            }
            $omiInfo = $orderMaterialItemService->getInfoById($orderMaterialItemId);
            if ($omiInfo['flag_del'] == 1) {
                return $this->Json(0, '此布号已删除！');
            }

            try {
                db()->startTrans();

                // 当前实际克重 =（缩水前重量/kg - 纸筒重量/kg)/(缩后米长 X （缩后布封 / 100)) X1000
                $trueWeight = round(($weightShrink - $weightPage) / ($length * ($trueFabricWidth / 100)) * 1000, 2);
                // 公司克重
                $materialInfo = $materialService->getInfoById($materialId, "weight,name,color");
                $weight = $materialInfo['weight'];
                // 克重超标率
                $weightOver = round(($trueWeight - $weight), 2);

                $omiInfo = $orderMaterialItemService->getInfoById($orderMaterialItemId);
                if ($omiInfo['need_checkcloth'] == 1 && $omiInfo['is_checkcloth'] == 0) {
                    return $this->Json(0, '请验布完成再操作！');
                }
                $insData = [
                    'order_id' => 0,
                    'client_ordernum' => '',
                    'stock_m_type' => 1,
                    'order_material_id' => $omInfo['mid'],
                    'type' => 2,
                    'order_material_item_id' => $orderMaterialItemId,
                    'cloth_num' => $clothNum,
                    'material_id' => $materialId,
                    'stalls_id' => arrayGet($omiInfo, 'stalls_id', 0),
                    'length' => round($length, 2),
                    'length_shrink' => round($lengthShrink, 2),
                    'true_fabric_width' => round($trueFabricWidth, 2),
                    'fabric_width_shrink' => round($fabricWidthShrink, 2),
                    'weight_shrink' => round($weightShrink, 2),
                    'weight_page' => round($weightPage, 2),
                    'edge_damage' => intval($edgeDamage),
                    'is_rejects' => $rejectsLength > 0 ? 1 : 0,
                    'rejects_ids' => $rejectsIds ? implode(',', $rejectsIds) : '',
                    'rejects_length' => round($rejectsLength, 2),
                    'true_weight' => $trueWeight,
                    'weight_over' => $weightOver,
                    'admin_id' => ADMIN_ID,
                    'create_time' => time(),
                    'update_time' => time(),
                ];
                $checkclothShrinkId = db('checkcloth_shrink')->insertGetId($insData);

                // 标记布号已缩水
                if ($orderMaterialItemId) {
                    $omiData = [
                        'shrink_id' => $checkclothShrinkId,
                        'is_shrink' => 1,
                        'shrink_time' => time(),
                        'update_time' => time()
                    ];
                    db('order_material_item')->where('id', $orderMaterialItemId)->update($omiData);
                }

                // 多料判断及处理
//                $checkclothShrinkService->excess($orderId, $materialId);

                // 更新布号米长
                $orderMaterialItemService->updateLength(0, 0, $omInfo['mid']);

                // 同步数据
                $checkclothShrinkService->syncData_stock_m_type_1($omInfo['mid'], 2);
                $orderMaterialService->updateCaichuangStatusV2(0, $omInfo['mid'],$this);
                $exception = 0;
                $msg = "";
                $dif1 = $orderMaterialService->checkShrinkLossStatus1($omInfo['mid']);
                if ($dif1) {
                    $exception = 1;//缩水1损耗大于0.02 true=1 ,false=0
                    $msg = "该单物料亏损严重，差异" . $dif1 . "公斤</br>";
                }
                $dif2 = $orderMaterialService->checkShrinkLossStatus2($omInfo['mid']);
                if ($dif2) {
                    $exception = 1;
                    $msg = $msg . "该单物料亏损严重，差异" . $dif2 . "克重";
                }
                $this->addOrderLog(0, '', "保存物料[" . getMaterialName($omInfo['material_id']) . "]布号{$clothNum}缩水数据，缩水记录ID {$checkclothShrinkId}", ['type' => 1, 'order_material_id' => $omInfo['mid']]);
                db()->commit();
                return $this->Json(1, '操作成功', ['exception' => $exception, 'msg' => $msg]);
            } catch (\Exception $e) {
                db()->rollback();
                return $this->Json(0, '操作失败，' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
            }
        }

    }

    /**
     * 缩水任务单
     *
     * @author KING
     * @date 2020年5月26日
     *
     */
    public function task() {
    	if ($this->request->isAjax()) {
			$clientOrdernum    = $this->request->param('client_ordernum/s');
			$createDateRange    = $this->request->param('create_time/s');
    		$startTime = strtotime(date("Y-m-d 00:00:00"));
    		$endTime = $startTime+86400-1;

    		$lastUpdateTime = $this->request->param('update_time/d', 0);
    		$dbUpdateTime = db('order_material_item')->order('update_time desc')->value('update_time');
    		if ($dbUpdateTime && $dbUpdateTime == $lastUpdateTime && !isset($clientOrdernum)) {
    			return $this->Json(0, "数据无变更！", ['update_time' => $dbUpdateTime]);
    		}

    		$checkclothShrinkService = new CheckclothShrinkService();

    		// 未完成任务列表
			$whereBefore=$where=[];
			$whereBefore[]=$where[]=['o.status' , '<>' ,99];
    		$whereBefore = [
    			['omi.need_shrink', '=', 1],
    			['omi.is_shrink', '=', 0],
    			['omi.is_return', '=', 0],
				['omi.is_shrink_outgo', '=', 0],
				['o.status', 'in', '0,1'],
    		];
            //订单加一级
            order_level($whereBefore,'o.');
			if ($clientOrdernum != '') {
    			$whereBefore[] = ['o.client_ordernum','like', "%".$clientOrdernum."%"];
    		}
			if ($createDateRange != '') {
				list($startT, $endT) = array_map('strtotime', explode('~', $createDateRange));
				$whereBefore[] = ['omi.create_time', 'between', [$startT, $endT+86399]];
			}
    		// 排除江西兴国工厂
    		$excludeIds = trim(config('mp.shrink_task_exclude_factory_id'));
    		if ($excludeIds != '') {
    			$whereBefore[] = ['o.factory_id', 'not in', $excludeIds];
    		}
    		$field = "omi.id as omi_id,o.outgo_status,o.status,o.id,o.shipment_time,o.client_ordernum,om.tiaoshu,om.caigou_status,omi.cloth_num,m.name,m.color,omi.create_time";
    		$todoList = db('order_material_item omi')
    		->join('order o', 'o.id = omi.order_id')
    		->join('material m', 'm.id = omi.material_id')
    		->join('order_material om', 'om.mid = omi.order_material_id')
    		->where($whereBefore)->order('om.caigou_status desc, o.caichuang_status desc, o.caichuang_over_time asc, o.shipment_time asc, omi.id asc')->field($field)->select();
    		foreach ($todoList as $k => $v) {
    			$todoList[$k]['type_name'] = '缩水';
    			$todoList[$k]['caigou_status_text'] = $v['caigou_status'] ? '是' : '否';
    			$todoList[$k]['shipment_time'] = date('n月j日', $v['shipment_time']);
    			$todoList[$k]['create_time'] = date('n月j日', $v['create_time']);
    		}

    		// 已完成任务列表
    		$where = [
    			['omi.need_shrink', '=', 1],
    			['omi.is_shrink', '=', 1],
    			['omi.shrink_time', 'between', [$startTime, $endTime]],
    		];
            //订单加一级
            order_level($where,'o.');
    		// 排除江西兴国工厂
    		if ($excludeIds != '') {
    			$where[] = ['o.factory_id', 'not in', $excludeIds];
    		}
    		$field = "o.shipment_time,o.client_ordernum,om.tiaoshu,om.caigou_status,omi.cloth_num,m.name,m.color,omi.create_time,omi.shrink_time as over_time,omi.is_return,cs.true_fabric_width,cs.length,cs.true_weight";
    		$doneList = db('order_material_item omi')
    		->join('order o', 'o.id = omi.order_id')
    		->join('material m', 'm.id = omi.material_id')
    		->join('order_material om', 'om.mid = omi.order_material_id')
    		->join('checkcloth_shrink cs', 'cs.id = omi.checkcloth_id')
    		->where($where)->order('cs.create_time desc')->field($field)->select();
    		foreach ($doneList as $k => $v) {
    			$doneList[$k]['type_name'] = '缩水'.($v['is_return']?'/退料':'');
    			$doneList[$k]['shipment_time'] = date('n月j日', $v['shipment_time']);
    			$doneList[$k]['create_time'] = date('n月j日', $v['create_time']);
    			$doneList[$k]['over_time'] = date('n月j日', $v['over_time']);
    			$doneList[$k]['caigou_status_text'] = $v['caigou_status'] ? '是' : '否';
    		}

    		// 统计（待处理，当日完成率，预计完成时间，当日来料总数，上月未完成总数）
    		$todoNum = count($todoList);	// 待处理
    		$todayOverRate = '100%';	// 今日完成率
    		$planOverTime = '';	// 预计完成时间
    		$monthJxNum = 0;//本月江西工厂数
    		$todayTotalNum = 0;	// 今日来料总数
    		$monthTotalNum = 0;	// 本月来料总数
    		$lastMonthTodoTotalNum = 0;	// 上月未完成总数
    		$thisMonthTodoTotalNum = 0;	// 本月未完成总数

    		// 今日完成率
    		$todayOverNum = count($doneList);	// 今日完成数
    		if ($todayOverNum+$todoNum > 0) {
    			$todayOverRate = round($todayOverNum*100/($todayOverNum+$todoNum), 2) . '%';
    		}

    		$lastMonthStart = strtotime(date('Y-m-01 00:00:00', strtotime('-1 month')));
    		$lastMonthEnd = strtotime(date("Y-m-1 00:00:00"))-1;
    		$monthStart = strtotime(date("Y-m-1 00:00:00"));

    		// 今日来料总数
    		$where = [
    			['need_checkcloth', '=', 1],
    			['create_time', 'between', [$startTime, $endTime]],
    		];
    		$todayTotalNum = db('order_material_item')->where($where)->count(1);

    		// 本月来料总数
    		$where = [
    			['need_checkcloth|need_shrink', '=', 1],
    			['create_time', '>=', $monthStart],
    		];
    		$monthTotalNum = db('order_material_item')->where($where)->count(1);

    		//本月江西兴国工厂
    		$monthJxNum = 0;
    		if ($excludeIds) {
	    		$where = [
	    			['o.factory_id', 'in', $excludeIds],
	    			['omi.create_time', '>=', $monthStart],
	    		];
	    		$monthJxNum = db('order_material_item omi')->join('order o', 'o.id = omi.order_id')->where($where)->count(1);
    		}

    		// 上月未完成总数
    		$where = [
    			['create_time', 'between', [$lastMonthStart, $lastMonthEnd]],
    		];
    		$lastMonthTodoTotalNum = db('order_material_item')->where('need_checkcloth = 1 and is_checkcloth = 0 or need_shrink = 1 and is_shrink = 0')->where($where)->count(1);

    		// 本月未完成总数
    		$where = [
    			['create_time', '>=', $monthStart],
    		];
    		$thisMonthTodoTotalNum = db('order_material_item')->where('need_checkcloth = 1 and is_checkcloth = 0 or need_shrink = 1 and is_shrink = 0')->where($where)->count(1);

    		// 预计完成时间
    		$planOverTime = $checkclothShrinkService->calPlanOverTime(2, $todoNum);

    		$d = [
    			'todoList' => $todoList,
    			'doneList' => $doneList,
    			'todoNum' => $todoNum,
    			'todayOverRate' => $todayOverRate,
    			'planOverTime' => $planOverTime,
    			'monthTotalNum' => $monthTotalNum,
    			'monthJxNum' => $monthJxNum,
    			'todayTotalNum' => $todayTotalNum,
    			'lastMonthTodoTotalNum' => $lastMonthTodoTotalNum,
    			'thisMonthTodoTotalNum' => $thisMonthTodoTotalNum,
    			'updateTime' => $dbUpdateTime
    		];
    		return $this->Json(1, '获取成功！', $d);
    	}
    	return $this->assign([])->fetch();
    }

    /**
     * 缩水任务详情（已完成）
     *
     * @author KING
     * @date 2020年5月26日
     *
     */
    public function taskDetail() {
    	$systemUserKV = getSystemUserKV(null);
    	if ($this->request->isAjax()) {
    		$s = microtime(true);
    		$page       = $this->request->param('page/d', 1);
    		$limit      = $this->request->param('limit/d', 20);
    		$adminId      = $this->request->param('admin_id/d', 0);
			$clientOrdernum    = $this->request->param('client_ordernum/s');
    		$where = [
    			['o.status', 'in', [0, 1]],
    			['cs.type', '=', 2]
    		];
			if ($clientOrdernum != '') {
    			$where[] = ['cs.client_ordernum','like', "%".$clientOrdernum."%"];
    		}
    		if ($adminId) {
    			$where[] = ['cs.admin_id', '=', $adminId];
    		}
    		$field = "cs.*,o.factory_id,o.sku,o.group_id,o.client_ordernum,o.shipment_time,o.sku,m.name material_name,m.color,omi.create_time as come_time,om.tiaoshu";
    		$order = "cs.id desc";
    		$count = db('checkcloth_shrink cs')
    		->join('order o', 'o.id = cs.order_id')
    		->join('material m', 'm.id = cs.material_id')
    		->where($where)->count();

    		$list = db('checkcloth_shrink cs')
    		->join('order o', 'o.id = cs.order_id')
    		->join('material m', 'm.id = cs.material_id')
    		->join('order_material_item omi', 'omi.id = cs.order_material_item_id')
    		->join('order_material om', 'omi.order_material_id = om.mid')
    		->where($where)->field($field)->order($order)->page($page)->limit($limit)->select();

    		foreach ($list as $k => $v) {
    			$v['type_text'] = '缩水' . ($v['is_return'] ? '/退料' : '');
    			$v['shipment_time_text'] = $v['shipment_time'] ? date('Y-m-d H:i', $v['shipment_time']) : '';
    			$v['create_time_text'] = $v['create_time'] ? date('Y-m-d H:i', $v['create_time']) : '';
    			$v['come_time_text'] = $v['come_time'] ? date('Y-m-d H:i', $v['come_time']) : '';

    			$v['tiaoshu'] = $v['tiaoshu'];
    			$v['true_weight'] = 0;
    			if ($v['type'] == 2 && $v['length_shrink'] > 0 && $v['fabric_width_shrink'] > 0) {
    				$v['true_weight'] = round(($v['weight_shrink'] - $v['weight_page']) * 1000 / ($v['length_shrink'] * $v['fabric_width_shrink'] / 100), 2);
    			}

    			if ($v['type'] == 1) {
    				$v['weight_shrink'] = '';
    				$v['weight_page'] = '';
    				$v['true_weight'] = '';
    			}

    			$v['is_return_text'] = $v['is_return']?'是':'否';

    			$list[$k] = $v;
    		}

    		$data['data'] = $list;
    		$data['count'] = $count;
    		$data['code'] = 0;
    		$data['msg'] = '';
    		$e = microtime(true);
    		$data['cost'] = $e-$s;
    		return json($data);
    	}
    	$assign = [
    		'userList' =>[0 => '请选择'] + db('checkcloth_shrink cs')->join('system_user su', 'cs.admin_id = su.id')->where('type', 2)->distinct(true)->field('cs.admin_id')->column('su.nick','cs.admin_id'),
    	];
    	return $this->assign($assign)->fetch();
    }

	/**
     * 缩水外发
     *
     * @date 2020年11月04日
     *
     */
	public function shrinkOugo(){
		$orderId  = $this->request->param('order_id/d', 0);
		$omiId  = $this->request->param('omi_id/d', 0);
		$upData = [
			'is_shrink_outgo' => 1,
			'length' => 8888,
			'is_shrink' => 1,
			'shrink_time' => time(),
			'update_time' => time(),
		];
		$ret = db('order_material_item')->where('id', $omiId)->update($upData);

		$orderMaterialItemService = new OrderMaterialItemService();
		$omiInfo = $orderMaterialItemService->getInfoById($omiId, 'material_id,cloth_num');

		$this->addOrderLog($orderId, '', "设置物料[".getMaterialName($omiInfo['material_id'])."]布号{$omiInfo['cloth_num']}缩水外发");
		if ($ret) {
			return $this->Json(1, '设置缩水外发成功');
		} else return $this->Json(0);
	}
}